<template>
  <div class="app-container">
    <h1 style="text-align: center">学员信息统计</h1>
    <div ref="chart" style="width: 100%; height: 500px;"></div>
  </div>
</template>

<script>
import { page as getStudentList } from '@/api/student.js'
import { findAll as getGradeList } from '@/api/grade.js'
import * as echarts from 'echarts'

export default {
  data() {
    return {
      chart: null,
      gradeList: [],
      studentList: []
    }
  },
  mounted() {
    this.initChart()
    this.fetchData()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.chart) {
      this.chart.dispose()
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart)
    },
    async fetchData() {
      try {
        const [gradeRes, studentRes] = await Promise.all([
          getGradeList(),
          getStudentList('', '', '', 1, 9999)
        ])
        // 打印响应数据
        console.log('年级数据:', gradeRes)
        console.log('学生数据:', studentRes)

        if (gradeRes.data && gradeRes.data.data && studentRes.data && studentRes.data.data) {
          this.gradeList = gradeRes.data.data
          this.studentList = studentRes.data.data.rows
          console.log('年级列表:', this.gradeList)
          console.log('学生列表:', this.studentList)
          this.renderChart()
        } else {
          throw new Error('返回数据格式不正确')
        }
      } catch (error) {
        console.error('获取数据失败:', error)
        if (this.$message) {
          this.$message.error(`获取数据失败，请稍后重试。错误详情: ${error.message}`)
        }
      }
    },
    renderChart() {
      const gradeStudentCount = this.gradeList.map(grade => {
        const count = this.studentList.filter(student => student.gradeid === grade.gradeid).length
        return {
          value: count,
          name: grade.gradename
        }
      }).filter(item => item.value > 0)
      // 打印处理后的数据
      console.log('年级学员统计数据:', gradeStudentCount)

      const option = {
        tooltip: {
          trigger: 'item'
        },
        series: [
          {
            name: '学员数量',
            type: 'pie',
            radius: '50%',
            data: gradeStudentCount,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      console.log('ECharts 配置:', option)
      this.chart.setOption(option)
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize()
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
